package com.daocao.hua.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.daocao.hua.R;
import com.daocao.hua.adapter.SelectDateV3Adapter;
import com.daocao.hua.adapter.SelectMoneyV3Adapter;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.DealApplyV3Bean;
import com.daocao.hua.api.bean.DealEstimateV3Bean;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.UserGlobal;
import com.daocao.hua.event.ChangeHomePagerEvent;
import com.daocao.hua.event.OnHomeEventMsg;
import com.daocao.hua.model.DealEstimateV3Model;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.Spans;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.MoneyUseV3Dialog;
import com.daocao.hua.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class SelectMoneyV3Activity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.list_money)
    RecyclerView listMoney;
    @BindView(R.id.list_date)
    RecyclerView listDate;
    @BindView(R.id.txt_money_use)
    TextView txtMoneyUse;
    @BindView(R.id.txt_money_arrive)
    TextView txtMoneyArrive;
    @BindView(R.id.txt_money_need_pay)
    TextView txtMoneyNeedPay;
    @BindView(R.id.txt_borrow_date)
    TextView txtBorrowDate;
    @BindView(R.id.txt_loan_date)
    TextView txtLoanDate;
    @BindView(R.id.txt_bank)
    TextView txtBank;
    @BindView(R.id.btn_agree)
    ImageView btnAgree;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.txt_place)
    TextView txtPlace;
    private Unbinder unbinder;
    private MoneyUseV3Dialog moneyUseV3Dialog;
    private String moneyUseId;
    private String realName;
    private SelectDateV3Adapter selectDateV3Adapter;
    private SelectMoneyV3Adapter selectMoneyV3Adapter;
    private String selectMoney;
    private String selectDate;
    private boolean isAgree = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_money_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("选择金额");
        txtRight.setText("LV" + PreferenceUtils.getInt(Application.getInstance(), Const.KEY.LEVEL, 1));
        txtRight.setVisibility(View.VISIBLE);
        moneyUseV3Dialog = new MoneyUseV3Dialog(this).setOnSelect(new MoneyUseV3Dialog.OnSureListener() {
            @Override
            public void onSure(String id, String name) {
                moneyUseId = id;
                txtMoneyUse.setText(name);
            }
        });
        Spanned span = Spans.with(this).font("相应等级对应着相应借款金额，最高可达5000元。认证越多，额度越高!", getResources().getDimensionPixelSize(R.dimen.x24), 0xffD8DBE9).
                font("点击获取更高额度>>>", getResources().getDimensionPixelSize(R.dimen.x24), 0xff4C81FF).
                build();
        txtTips.setText(span);

        selectMoneyV3Adapter = new SelectMoneyV3Adapter(this);
        selectMoneyV3Adapter.setOnChooseListener(new SelectMoneyV3Adapter.OnChooseListener() {
            @Override
            public void onClick(String name) {
                selectMoney = name;
                getDealCalculator(selectMoney, selectDate);
            }
        });
        listMoney.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        listMoney.setAdapter(selectMoneyV3Adapter);

        selectDateV3Adapter = new SelectDateV3Adapter(this);
        selectDateV3Adapter.setOnChooseListener(new SelectDateV3Adapter.OnChooseListener() {
            @Override
            public void onClick(String name) {
                selectDate = name;
                getDealCalculator(selectMoney, selectDate);
            }
        });
        listDate.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        listDate.setAdapter(selectDateV3Adapter);
        getDealTypes();
    }

    private void getBankList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        Api.api_service.getBankList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (!TextUtils.isEmpty(result.getReal_name())) {
                        UserGlobal.setRealName(result.getReal_name());
                        realName = result.getReal_name();
                    }
                    checkAll();
                    if (result.getBanks() == null || result.getBanks().size() <= 0) {
                        return;
                    }
                    txtBank.setText(result.getBanks().get(0).getBankcard());

                });
    }

    private void getDealApplyV3(String borrow_amount, String borrow_limit) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        DealApplyV3Bean item = new DealApplyV3Bean();
        item.borrow_amount = borrow_amount;
        item.borrow_limit = borrow_limit;
        Api.api_service.getDealApplyV3(item).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {


                    switch (result.getStatus()) {
                        case 1:
                        case 2:
                            UserGlobal.setDealId(result.deal_id);
                            UserGlobal.setUseType(moneyUseId);
                            UserGlobal.info.deal_id = result.deal_id;
                            UserGlobal.info.type = 1;
                            Intent intent = new Intent(this, LoanAgreementActivity.class);
                            startActivity(intent);
                            finish();
                            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                            break;
                        case 3:
                        case 4:
                        case 5:
                            Map<String, String> map = new HashMap<>();
                            map.put("type", Const.SendType.UPDATE);
                            EventBus.getDefault().post(new OnHomeEventMsg(map));
                            Util.startActivity(this, MainActivityNew.class);
                            finish();
//                            Intent intent1 = new Intent(this, NewApplyForActivity.class);
//                            startActivity(intent1);
//                            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
//                            finish();
                            break;
                        case 6:
                            showRepayDialog(result.getMsg());
                            break;
                    }

                });
    }

    private void showRepayDialog(String msg) {

        Dialog.showRepayTipsDialog(this, msg, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                sendEventBus();
            }

            @Override
            public void cancel() {

            }
        });

    }

    private void sendEventBus() {

        Map<String, String> map = new HashMap<>();
        map.put("type", Const.SendType.SWITCH_PAGE);
        map.put("currentIndex", Const.View.REPAY_VIEW + "");
        EventBus.getDefault().post(new OnHomeEventMsg(map));
        Util.startActivity(this, MainActivityNew.class);
        finish();
    }

    private void getDealTypes() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        Api.api_service.getDealTypesV3().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.data.borrow_limit != null && result.data.borrow_limit.size() != 0) {
                        selectDate = result.data.borrow_limit.get(0);
                        selectDateV3Adapter.update(result.data.borrow_limit);
                    }
                    if (result.data.borrow_amount != null && result.data.borrow_amount.size() != 0) {
                        selectMoney = result.data.borrow_amount.get(0).borrow_amount;
                        selectMoneyV3Adapter.update(result.data.borrow_amount);
                    }

                    moneyUseV3Dialog.setData(result.data.use_type);

                    txtMoneyArrive.setText(result.data.repay_info.money);
                    txtMoneyNeedPay.setText(result.data.repay_info.repay_money);
                    txtBorrowDate.setText(result.data.repay_info.borrow_date);
                    txtLoanDate.setText(result.data.repay_info.repay_date);
                    txtPlace.setText(result.data.loaner);
                });
    }

    private void getDealCalculator(String borrow_amount, String borrow_limit) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        selectDateV3Adapter.setCanEdit(false);
        selectMoneyV3Adapter.setCanEdit(false);
        DealEstimateV3Bean item = new DealEstimateV3Bean();
        item.borrow_amount = borrow_amount;
        item.borrow_limit = borrow_limit;
        Api.api_service.getDealEstimateV3(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                        selectDateV3Adapter.setCanEdit(true);
                        selectMoneyV3Adapter.setCanEdit(true);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setCalculatorData(result.data);
                });
    }

    private void setCalculatorData(DealEstimateV3Model.DataBean data) {
        txtMoneyArrive.setText(data.money + "元");
        txtMoneyNeedPay.setText(data.repay_money + "元");
        txtBorrowDate.setText(data.borrow_date);
        txtLoanDate.setText(data.repay_date);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getBankList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        unbinder = null;
    }

    private boolean checkAll() {
        if (!TextUtils.isEmpty(selectMoney) &&
                !TextUtils.isEmpty(selectDate) &&
                !TextUtils.isEmpty(moneyUseId) &&
                !TextUtils.isEmpty(UI.toString(txtBank)) &&
                isAgree) {
            btnSubmit.setSelected(true);
            return true;
        } else {
            btnSubmit.setSelected(false);
            return false;
        }

    }

    @OnClick({R.id.txt_money_use, R.id.btn_back, R.id.txt_bank, R.id.btn_agree, R.id.txt_agree, R.id.btn_submit, R.id.txt_tips})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_money_use:
                moneyUseV3Dialog.show();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_bank:
                if (TextUtils.isEmpty(realName)) {
                    getBankList();
                    return;
                }
                Intent bankIntent = new Intent(this, V3BankListActivity.class);
                bankIntent.putExtra("realName", realName);
                startActivity(bankIntent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_agree:
                isAgree = !isAgree;
                if (isAgree) {
                    btnAgree.setImageResource(R.mipmap.img_pay_cb_open);

                } else {
                    btnAgree.setImageResource(R.mipmap.img_pay_cb_close);
                }
                checkAll();
                break;
            case R.id.txt_agree:
                showDialog();
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(selectMoney)) {
                    ToastUtil.makeText(this, "请选择借款金额");
                    getDealTypes();
                    return;
                }
                if (TextUtils.isEmpty(selectDate)) {
                    ToastUtil.makeText(this, "请选择借款期限");
                    getDealTypes();
                    return;
                }
                if (TextUtils.isEmpty(moneyUseId)) {
                    ToastUtil.makeText(this, "请选择借款用途");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtBank))) {
                    ToastUtil.makeText(this, "请选择收款银行卡");
                    return;
                }
                if (!isAgree) {
                    ToastUtil.makeText(this, "请勾选阅读并同意《花毛线借款须知》");
                    return;
                }
                getDealApplyV3(selectMoney, selectDate);
                break;
            case R.id.txt_tips:
//                Util.startActivity(this, V3AllIdentityActivity.class);
                EventBus.getDefault().post(new ChangeHomePagerEvent(1));
                finish();
                break;
        }
    }

    public void showDialog() {
//        if (item == null) {
//            return;
//        }
//        if (item.data != null && item.data.size() != 0) {
//            Dialog.showLoanDialoLg(this, item.data);
//        }
        Intent intent = new Intent(this, DialogActivity.class);
        intent.putExtra("url", "http://app.api.hua.dob500.com/views/notes");
        startActivity(intent);

    }
}
